package com.jtyoui.config;

import com.jtyoui.intecepter.HttpHandShakeInterceptor;
import com.jtyoui.intecepter.SocketChannelInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.ChannelRegistration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

/**
 * config web socket chat
 * 网页通讯配置文件
 *
 * @author jtyoui
 * @version 18.5.23
 */
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    /**
     * register an endpoint. publish or subscribe to a message
     * 注册端点，发布或者订阅消息的时候连接此端点
     *
     * @param registry 注册
     *                 setAllowedOrigins Non-required . * indicates that any geographic connection is allowed.
     *                 setAllowedOrigins 非必须。*表示允许任何的地域连接
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/endpoint-webSocket").addInterceptors(new HttpHandShakeInterceptor()).setAllowedOrigins("*").withSockJS();
    }

    /**
     * configure message agent
     * 配置消息代理
     *
     * @param registry 注册
     */
    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.enableSimpleBroker("/topic", "/chat");//path prefix pushed by the  server to the client 服务端发给客户端路径前缀
        registry.setApplicationDestinationPrefixes("/app");//the prefix that client sends  to the server data 客户端发给服务端数据前缀
    }

    @Override
    public void configureClientInboundChannel(ChannelRegistration registration) {
        registration.interceptors(new SocketChannelInterceptor());
    }

    @Override
    public void configureClientOutboundChannel(ChannelRegistration registration) {
        registration.interceptors(new SocketChannelInterceptor());
    }
}
